package hu.raholec.service.jackrabbit;

import hu.raholec.service.ServiceException;
import java.io.File;
import java.io.IOException;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import org.apache.jackrabbit.core.RepositoryImpl;
import org.apache.jackrabbit.core.TransientRepository;
import org.apache.jackrabbit.core.config.RepositoryConfig;
import org.springframework.core.io.ClassPathResource;

public class JackrabbitUtil {

    private Repository repository;
    private String login;
    private String password;

    public JackrabbitUtil(String repositoryXmlUrl, String login, String password) {

        this.login = login;
        this.password = password;

        repository = new TransientRepository();

//        try {
//            ClassPathResource classPathResource = new ClassPathResource("repository");            
//            RepositoryConfig config = RepositoryConfig.create(new File(repositoryXmlUrl), classPathResource.getFile());
//            repository = RepositoryImpl.create(config);
//        } catch (IOException e) {
//            throw new ServiceException(e);
//        } catch (RepositoryException e) {
//            throw new ServiceException(e);
//        }
    }

    public Session login() {
        System.out.println("JackrabbitUtil login in progress...");
        try {
            Session s = repository.login(new SimpleCredentials(login, password.toCharArray()));
            System.out.println("JackrabbitUtil login OK.");
            return s;
        } catch (RepositoryException e) {
            throw new ServiceException(e);
        }
    }

    public void logout(Session session) {
        System.out.println("JackrabbitUtil logout in progress...");
        if (session == null || !session.isLive()) {
            return;
        }
        session.logout();
        System.out.println("JackrabbitUtil logout OK.");
    }
}
